<?php
/**
 * Created by WarCraft3
 * User: WarCraft3
 * Date: 2021/9/16
 * Time: 16:45
 */

namespace app\admin\controller;
use app\common\controller\Backend;
use vod\Request\V20170321 as vod;
require_once 'voduploadsdk/Autoloader.php';
date_default_timezone_set('PRC');

use think\Exception;
class Aliupload extends Backend
{
    // 测试上传本地视频
    public function testUploadLocalVideo($filePath)
    {
         $accessKeyId = 'LTAI5t5ey3QJhEHW3979gsqo';
         $accessKeySecret = 'YtaUsPNqywcMMTgDwvXaDZcTS6N9lH';
         //$filePath = 'uploads/1.mp4';
        try {
            $uploader = new \AliyunVodUploader($accessKeyId, $accessKeySecret);
            $uploadVideoRequest = new \UploadVideoRequest($filePath, 'testUploadLocalVideo via PHP-SDK');
            $uploadVideoRequest->setCateId(4163);

            $uploadVideoRequest->setStorageLocation('outin-907df0a21c4011ecab3a00163e038793.oss-cn-beijing.aliyuncs.com');

            //$uploadVideoRequest->setTemplateGroupId('6ae347b0140181ad371d197ebe289326');
            $userData = array(
                "MessageCallback"=>array("CallbackURL"=>"https://demo.sample.com/ProcessMessageCallback"),
                "Extend"=>array("localId"=>"1", "test"=>"www")
            );
            $uploadVideoRequest->setUserData(json_encode($userData));
            $res = $uploader->uploadLocalVideo($uploadVideoRequest);
            sleep(5);
            list($ret,$time) = $this->getAddress($res);
            return [$ret,$time];
        } catch (Exception $e) {
            return false;
//            printf("testUploadLocalVideo Failed, ErrorMessage: %s\n Location: %s %s\n Trace: %s\n",
//                $e->getMessage(), $e->getFile(), $e->getLine(), $e->getTraceAsString());
        }
    }

    /*
     * 根据视频id 获取视频播放地址等信息
     * */
    private function getAddress($videoId)
    {
        // 注意捕获异常
        try {
            $accessKeyId = 'LTAI5t5ey3QJhEHW3979gsqo';
            $accessKeySecret = 'YtaUsPNqywcMMTgDwvXaDZcTS6N9lH';
            $uploader = new \AliyunVodUploader($accessKeyId, $accessKeySecret);
            $client = $uploader->initVodClient();
            $playInfo = $this->getPlayInfo($client, $videoId);
            if ($playInfo->VideoBase->Status == 'Normal'){//成功
                return [$playInfo->PlayInfoList->PlayInfo[0]->PlayURL,$playInfo->PlayInfoList->PlayInfo[0]->Duration];
            }
        } catch (Exception $e) {
            return false;
        }
    }


    private function getPlayInfo($client, $videoId) {
        $request = new vod\GetPlayInfoRequest();
        $request->setVideoId($videoId);
        $request->setAuthTimeout(3600*24);
        $request->setAcceptFormat('JSON');
        return $client->getAcsResponse($request);
    }


}